import {rules, zoneGeoms} from './testData.js'
import { has } from 'mobx'
import { WebSocket } from 'ws'
import { monitorZoneStore, monitorTkoStore } from './store.js'
import * as R from 'ramda'
const socket = new WebSocket('ws://127.0.0.1:7788')

// initialize zoneStore from rules
rules.map(rule=> {
  monitorZoneStore.initZone(rule.zoneId, rule)
})

const dispatch = {
  // true: in false: out
  "zone": {
    paramPath: ["zoneId"],
    true: monitorZoneStore.addZoneRule, 
    false: monitorZoneStore.removeZoneRule
  },
  "tko": {
    paramPath: [],
    "keep_out": {
      true: monitorTkoStore.addTkoRule, 
      false: monitorTkoStore.removeTkoRule
    },
    "keep_in": {
      true: monitorTkoStore.removeTkoRule,
      false: monitorTkoStore.addTkoRule, 
    },
    "in_area_pause_limit": {
      true: monitorTkoStore.updateTkoRule,
      false: monitorTkoStore.removeTkoRule
    }
  }
}

function check(obj) {
  rules.map(rule=> {
    let trackTarget = rule.check_on ==="zone"? 
      dispatch["zone"] 
      : 
      dispatch["tko"][rule.name]
    
    let propPath = dispatch[rule.check_on].paramPath
    let param = R.view(R.lensPath(propPath), rule)
    let checkInOutArea = rule.checkFn(obj, zoneGeoms[rule.zoneId])
    trackTarget[checkInOutArea](param, obj)
  })
}


socket.onmessage = (ev) => {
  let evData = JSON.parse(ev.data)
  //check_rules(evData)
  check(evData)
  //console.log(JSON.stringify(toJS(monitorZoneStore)))
}
